package com.mobilnaElka.activities.calendar;

import java.util.ArrayList;

import plan.parser.Parser;
import plan.parser.classes.Subject;
import plan.parser.reader.Reader;
import android.app.*;
import android.content.*;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;

import com.mobilnaElka.AppConsts;
import com.mobilnaElka.activities.R;
import com.mobilnaElka.models.calendar.*;

public class CalendarsListActivity extends ListActivity {

	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		ArrayList<String> calendars = getCalendars(this);
		this.setListAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, calendars));

	}

	private ArrayList<String> getCalendars(CalendarsListActivity calendarsList) {
		ArrayList<String> cals = new ArrayList<String>();

		Cursor managedCursor = getManagedCursor();

		while (managedCursor.moveToNext()) {

			final String displayName = managedCursor.getString(managedCursor
					.getColumnIndex("displayName"));
			cals.add(displayName);

		}

		managedCursor.close();
		return cals;

	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		// Get the item that was clicked
		Object o = this.getListAdapter().getItem(position);
		String keyword = o.toString();

		int calId = getCalendarId(keyword);
		Toast.makeText(
				this,
				getString(R.string.calendar_timetable_was_saved_to) + " "
						+ keyword, Toast.LENGTH_LONG).show();

		SharedPreferences preferences = getSharedPreferences(
				AppConsts.SETTINGS_PREF, Context.MODE_PRIVATE);
		try {
			parseAndCreateEventsInCalendar(
					preferences.getString(Consts.SETTINGS_FILE_NAME, ""), calId);
		} catch (Exception e) {
			e.printStackTrace();
		}

		Intent intent = new Intent(CalendarsListActivity.this,
				CalendarSettingsActivity.class);
		startActivityForResult(intent, Activity.RESULT_OK);

	}

	private int getCalendarId(String keyword) {

		Cursor managedCursor = getManagedCursor();

		while (managedCursor.moveToNext()) {

			String displayName = managedCursor.getString(managedCursor
					.getColumnIndex("displayName"));

			if (displayName.equals(keyword)) {
				String id = managedCursor.getString(managedCursor
						.getColumnIndex("_id"));
				try {
					return Integer.parseInt(id);
				} catch (NumberFormatException nfe) {
					Log.e(AppConsts.TAGNAME, "Could not parse "
							+ nfe);
				}
			}
		}

		return 0;
	}

	public void parseAndCreateEventsInCalendar(String chosenFilePath, int calId)
			throws Exception {
		if (chosenFilePath != null) {
			Reader reader = new Reader(chosenFilePath);
			Parser parser = new Parser(reader.getReaderElements());
			parser.prepareFile();
			parser.parse();
			java.util.Iterator<Subject> it = parser.getSubjects().iterator();

			Uri EVENTS_URI = Uri.parse(getCalendarUriBase() + "events");
			ContentResolver cr = getContentResolver();

			while (it.hasNext()) {
				Subject subject = it.next();
				// add to calendar
				CalendarEvent event = new CalendarEvent(calId, subject);
				cr.insert(EVENTS_URI, event.getEvent());
			}
		}
	}

	public String getCalendarUriBase() {

		String calendarUriBase = null;
		Uri calendars = Uri.parse("content://calendar/calendars");
		Cursor managedCursor = null;
		try {
			managedCursor = managedQuery(calendars, null, null, null, null);
		} catch (Exception e) {
		}
		if (managedCursor != null) {
			calendarUriBase = "content://calendar/";
		} else {
			calendars = Uri.parse("content://com.android.calendar/calendars");
			try {
				managedCursor = managedQuery(calendars, null, null, null, null);
			} catch (Exception e) {
			}
			if (managedCursor != null) {
				calendarUriBase = "content://com.android.calendar/";
			}
		}
		managedCursor.close();
		return calendarUriBase;
	}

	private Cursor getManagedCursor() {
		Uri calendars = Uri.parse(getCalendarUriBase() + "/calendars");
		Cursor managedCursor = null;
		managedCursor = managedQuery(calendars, null, null, null, null);
		return managedCursor;
	}

	@Override
	public void onBackPressed() {
		Intent myIntent = new Intent(CalendarsListActivity.this,
				CalendarSettingsActivity.class);
		finish();
		startActivityForResult(myIntent, 0);

	}

}
